// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import App from './App';
import router from './router';
import 'babel-polyfill';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios';
import Qs from 'qs';
import store from './store/store';
Vue.use(ElementUI);
Vue.config.productionTip = false;
Vue.prototype.$bus = new Vue();
function getCookie (cname) {
  let name = cname + '=';
  let ca = document.cookie.split(';');
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') c = c.substring(1);
    if (c.indexOf(name) !== -1) return c.substring(name.length, c.length);
  }
  return '';
}
// 创建ajax
Vue.prototype.$axios = axios;
Vue.prototype.$bus.baseURL = '/api/';
Vue.prototype.axios = axios.create({
  baseURL: Vue.prototype.$bus.baseURL,
  timeout: 10000,
  withCredentials: true,
  // 这时候我们通过Qs.stringify转换为表单查询参数
  transformRequest: [function (data) {
    data = Qs.stringify(data);
    return data;
  }],
  // 设置Content-Type
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'X-XSRF-TOKEN': getCookie('XSRF-TOKEN')
  }
});
Vue.prototype.axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          location.replace('/login');
          break;
      }
    }
    return Promise.reject(error.response.data); // 返回接口返回的错误信息
  });
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
});
